/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.dubbo.dubboclient.aervice;

import com.api.MyExecption;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * QiNiuService
 * @author luo
 * @version 2017-10-12
 */
@Service
public class QiNiuPhotoService {


	private static String accessKey;

	private static String secretKey;

	private static String bucket;

	private static String realmName;

	static {
		accessKey = "Tg0coh9a85Hg9p0UDr3oQ8rRCn5mHvsZUH7j34hZ";
		secretKey = "RYn6gIxtAPDlAb3EQEacL4az6raezaTrCnDxTn34";
		bucket = "test";
		realmName = "p6agwvtwc.bkt.clouddn.com";

	}


	public String uploadPhoto(MultipartFile mulFile) throws MyExecption {

		if(StringUtils.isBlank(realmName)){
			throw new MyExecption("请配置图片域名");
		}
		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		//...其他参数参考类注释
		UploadManager uploadManager = new UploadManager(cfg);

		//默认不指定key的情况下，以文件内容的hash值作为文件名
		String fileName = UUID.randomUUID().toString().replaceAll("-","") + "." +mulFile.getOriginalFilename();
		String upToken = getToKen();

		try {
			Response response = uploadManager.put(mulFile.getBytes(), fileName, upToken);
			//解析上传成功的结果
			DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
			return realmName+File.separatorChar+putRet.key;

		} catch (QiniuException ex) {
			throw new MyExecption("文件上传失败");
//			Response r = ex.response;
//			System.err.println(r.toString());
		} catch (Exception e){
			throw new MyExecption("上传失败");
		}
	}

	//获得toKen
	public String getToKen() throws MyExecption {


		if(StringUtils.isBlank(accessKey) || StringUtils.isBlank(secretKey) || StringUtils.isBlank(bucket)){
			throw new MyExecption("图片服务器地址配置有误,请检查");
		}
		Auth auth = Auth.create(accessKey, secretKey);
		return auth.uploadToken(bucket);
	}

	/**
	 * 文件类型转换
	 */
	public File multipartToFile(MultipartFile multfile) {

		CommonsMultipartFile cf = (CommonsMultipartFile)multfile;
		//这个myfile是MultipartFile的
		DiskFileItem fi = (DiskFileItem) cf.getFileItem();
		File file = fi.getStoreLocation();
		return file;
	}

}